/**
 * elancom Corporation copy right 2012 - 2015  
 *   
 * $Header$
 * $Id$
 * $Author$
 * $Date$
 * $Revision$
 */
package com.elancom.framework.context;

import com.elancom.framework.BeanRepository;
import com.elancom.framework.config.AppConfig;
import com.elancom.framework.context.impl.StandardUserContext;

/**
 * @author elancom
 * @date 2012-7-13
 */
public class CurrentContext {
	private static ThreadLocal<CurrentContext> THREAD_LOCAL = new ThreadLocal<CurrentContext>();

	private UserContext userContext = null;

	private SessionContext sessionContext = null;

	private static SessionContextFactory sessionContextFactory = null;

	static {
		initSessionContextFactory();
	}

	public static CurrentContext getContext() {
		CurrentContext ctx = THREAD_LOCAL.get();
		if (ctx == null) {
			ctx = new CurrentContext();
			THREAD_LOCAL.set(ctx);
		}
		return ctx;
	}

	static void clear() {
		THREAD_LOCAL.remove();
		THREAD_LOCAL.set(null);
	}

	public UserContext getUserContext() {
		if (userContext == null) {
			userContext = new StandardUserContext();
		}
		return userContext;
	}

	/**
	 * 
	 */
	private static void initSessionContextFactory() {
		if (sessionContextFactory == null) {
			synchronized (CurrentContext.class) {
				if (sessionContextFactory == null) {
					try {
						sessionContextFactory = BeanRepository.getBean("sessionContextFactory");
					} catch (Exception e) {
						System.out.println("sessionContextFactory没有通过spring配置注入");
						e.printStackTrace();
						try {
							sessionContextFactory = (SessionContextFactory) Class.forName(AppConfig.getSessionContextFactory()).newInstance();
						} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e2) {
							e2.printStackTrace();
							throw new RuntimeException("不能创建sessionContextFactory,请查看配置.");
						}
					}
				}
			}
		}
	}

	public SessionContext getSessionContext() {
		if (sessionContext == null) {
			sessionContext = sessionContextFactory.factory();
		}
		return sessionContext;
	}

}
